package logic

import (
	"blog/blogrpc/blogrpc"
	"blog/blogrpc/internal/svc"
	"blog/blogrpc/models/cache"
	"blog/blogrpc/models/mysql"
	"blog/pkg"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserRegisterLogic) UserRegister(in *blogrpc.UserRegisterRequest) (*blogrpc.UserRegisterResponse, error) {
	// todo: add your logic here and delete this line

	get := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Val()
	if get != in.CaptCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}

	init := cache.Rdb.Get(l.ctx, "mobile"+in.Mobile).Val()
	if init != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("手机号已存在,请前去注册")
	}
	users := mysql.User{

		Username: in.Username,
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&users)
	return &blogrpc.UserRegisterResponse{
		Userid: int64(users.ID),
	}, nil
}
